// import { createChunk } from './createChunk.js'
// const CHUNK_SIZE = 1024 * 1024 * 5; // 1MB

// export async function cutFile(file) {
//     console.log('调用成功')
//     const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
//     const result = []
//     for (let i = 0; i < totalChunks; i++) {
//         const chunk = await createChunk(file, i, CHUNK_SIZE)
//         console.log('chuck:', chunk)
//         result.push(chunk)
//     }
//     return result
// }



const CHUNK_SIZE = 1024 * 1024 * 5; // 1MB
const THREAD_COUNT = navigator.hardwareConcurrency || 4; // 浏览器的硬件线程数

export async function cutFile(file) {
    return new Promise((resolve) => {
        const chunkCount = Math.ceil(file.size / CHUNK_SIZE);
        const threadChunkCount = Math.ceil(chunkCount / THREAD_COUNT);
        const result = []
        let finishedCount = 0

        for (let i = 0; i < THREAD_COUNT; i++) {
            // 创建一个线程，并分配任务
            const worker = new Worker('./worker.js', {
                type: 'module'
            });
            let end = (i + 1) * threadChunkCount
            let start = i * threadChunkCount
            if (end > chunkCount) {
                end = chunkCount
            }
            worker.postMessage({
                file,
                CHUNK_SIZE,
                startChunkIndex: start,
                endChunkIndex: end,
            })
            worker.onmessage = (e) => {
                for (let i = start; i < end; i++) {
                    result[i] = e.data[i - start]
                }
                worker.terminate()
                finishedCount++
                if (finishedCount === THREAD_COUNT) {
                    resolve(result)
                }
            }
        }
    })
}